package com.glory;

import com.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取session
        HttpSession session = req.getSession();
        //给session中存东西
        session.setAttribute("name", new Person("荣椿", 26));
        //获取session的ID
        String sessionId = session.getId();
        //判断session是不是新创建的
        if(session.isNew()){
            resp.getWriter().write(String.format("session创建成功，sessionID为：%s", sessionId));
        } else {
            resp.getWriter().write(String.format("session已存在，sessionID为：%s", sessionId));
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
